package com.art.museumbackend.controller;

import com.art.museumbackend.annotation.Log;
import com.art.museumbackend.entity.Result;
import com.art.museumbackend.entity.SystemLog;
import com.art.museumbackend.service.SystemLogService;
import com.art.museumbackend.utils.ResultUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/log")
public class LogController {

    @Autowired
    private SystemLogService systemLogService;

    @GetMapping("/{type}")
    public Result<Page<SystemLog>> getLogList(
            @PathVariable String type,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDateTime endTime,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Page<SystemLog> logs = systemLogService.getLogList(type, username, startTime, endTime, page, size);
        return ResultUtil.success(logs);
    }

    @GetMapping("/{type}/export")
    @Log(value = "导出日志", type = "operation")
    public ResponseEntity<byte[]> exportLogs(
            @PathVariable String type,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDateTime endTime) {
        
        byte[] data = systemLogService.exportLogs(type, username, startTime, endTime);
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "logs.xlsx");
        
        return ResponseEntity.ok()
                .headers(headers)
                .body(data);
    }

    @DeleteMapping("/clean/{type}/{days}")
    @Log(value = "清理日志", type = "operation")
    public Result<Void> cleanLogs(@PathVariable String type, @PathVariable int days) {
        if (days < 180) {
            return ResultUtil.fail("日志保存时间不能少于180天");
        }
        systemLogService.cleanLogs(type, days);
        return ResultUtil.successMsg("清理日志成功");
    }
} 